package mobi.hami.huapin.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求aop
 *
 * @author 阿飞 jijunjian@hami.mobi
 * @date 2018/5/31 12:52
 */
@Aspect
@Component
public class HttpAspect {

    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public  * mobi.hami.huapin.controller.*.*(..))")
    public void log()
    {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint)
    {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("url={}",request.getRequestURL());
        logger.info("method={}",request.getMethod());
        logger.info("ip={}",request.getRemoteAddr());
        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        logger.info("args={}",joinPoint.getArgs());

    }

    @After("log()")
    public  void  doAfter()
    {

    }

    @AfterReturning(returning = "object",pointcut = "log()")
    public  void doAfterReturnint(Object object)
    {
        logger.info("response={}",object.toString());
    }


    @AfterThrowing(value = "log()", throwing = "e")
    public void logException(JoinPoint joinPoint, Exception e) {
        String name = joinPoint.getSignature().getName();
        logger.info("AOP日志：【" + name + "】方法运行出现异常:" + e);
    }



}
